package boot.spring.controller;

import javax.servlet.http.HttpSession;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

import boot.spring.po.MSG;
import boot.spring.po.User;
import boot.spring.po.Staff;
import boot.spring.service.LoginService;
import boot.spring.service.MailUtils;
import java.util.Random;



@Controller
public class Login {
	@Autowired
	LoginService loginservice;
	
	@RequestMapping("/loginvalidate")
	public String loginvalidate(@RequestParam("username") String username, @RequestParam("password") String pwd, @RequestParam(value = "rememberMe", required = false) String rememberMe, HttpSession httpSession, HttpServletResponse response, Model model) {
		if (username == null || username.trim().isEmpty()) {
			model.addAttribute("errorMsg", "用户名不能为空");
			return "login";
		}
		if (pwd == null || pwd.trim().isEmpty()) {
			model.addAttribute("errorMsg", "密码不能为空");
			return "login";
		}
		String realpwd = loginservice.getpwdbyname(username);
		if (realpwd != null && pwd.equals(realpwd)) {
			long uid = loginservice.getUidbyname(username);
			httpSession.setAttribute("uid", uid);
			// 记住我功能
			if ("on".equals(rememberMe)) {
				Cookie cookie = new Cookie("rememberedUsername", username);
				cookie.setMaxAge(60 * 60 * 24 * 7); // 7天
				cookie.setPath("/");
				response.addCookie(cookie);
			} else {
				Cookie cookie = new Cookie("rememberedUsername", null);
				cookie.setMaxAge(0);
				cookie.setPath("/");
				response.addCookie(cookie);
			}
			return "chatroom";
		} else {
			model.addAttribute("errorMsg", "用户名或密码错误");
			return "login";
		}
	}
	
	@RequestMapping("/login")
	public String login(HttpServletRequest request, Model model) {
		String rememberedUsername = null;
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if ("rememberedUsername".equals(cookie.getName())) {
					rememberedUsername = cookie.getValue();
					break;
				}
			}
		}
		model.addAttribute("rememberedUsername", rememberedUsername);
		String msg = request.getParameter("msg");
		if (msg != null && !msg.isEmpty()) {
			model.addAttribute("infoMsg", msg);
		}
		return "login";
	}
	
	@RequestMapping("/logout")
	public String logout(HttpSession httpSession){
		return "login";
	}
	
	@RequestMapping(value="/currentuser",method = RequestMethod.GET)
	@ResponseBody
	public User currentuser(HttpSession httpSession){
		Long uid = (Long)httpSession.getAttribute("uid");
		String name = loginservice.getnamebyid(uid);
		return new User(uid, name);
	}
	
	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String registerPage() {
		return "register";
	}

	@RequestMapping("/register")
	public String register(Staff staff, Model model, HttpSession session, @RequestParam(value="emailCode", required=false) String emailCode) {
		// 验证用户输入
		if (staff.getUsername() == null || staff.getUsername().trim().isEmpty()) {
			model.addAttribute("msg", "用户名不能为空");
			return "register";
		}
		if (staff.getPassword() == null || staff.getPassword().trim().isEmpty()) {
			model.addAttribute("msg", "密码不能为空");
			return "register";
		}
		if (staff.getFirst_name() == null || staff.getFirst_name().trim().isEmpty()) {
			model.addAttribute("msg", "姓不能为空");
			return "register";
		}
		if (staff.getLast_name() == null || staff.getLast_name().trim().isEmpty()) {
			model.addAttribute("msg", "名不能为空");
			return "register";
		}
		if (staff.getEmail() == null || staff.getEmail().trim().isEmpty()) {
			model.addAttribute("msg", "邮箱不能为空");
			return "register";
		}
		
		// 校验邮箱验证码
		String code = (String) session.getAttribute("email_code");
		String addr = (String) session.getAttribute("email_code_addr");
		Long sendTime = (Long) session.getAttribute("email_code_time");
		if (code == null || addr == null || sendTime == null || !addr.equals(staff.getEmail())) {
			model.addAttribute("msg", "请先获取邮箱验证码");
			return "register";
		}
		if (System.currentTimeMillis() - sendTime > 5*60*1000) {
			model.addAttribute("msg", "验证码已过期，请重新获取");
			return "register";
		}
		if (emailCode == null || !emailCode.equals(code)) {
			model.addAttribute("msg", "验证码错误");
			return "register";
		}
		
		// 检查用户名是否已存在
		String realpwd = loginservice.getpwdbyname(staff.getUsername());
		if (realpwd != null) {
			model.addAttribute("msg", "用户名已存在");
			model.addAttribute("username", staff.getUsername());
			model.addAttribute("first_name", staff.getFirst_name());
			model.addAttribute("last_name", staff.getLast_name());
			model.addAttribute("email", staff.getEmail());
			return "register";
		}
		
		try {
			loginservice.insertUser(staff);
			model.addAttribute("msg", "注册成功，请登录");
			return "login";
		} catch (Exception e) {
			model.addAttribute("msg", "注册失败：" + e.getMessage());
			return "register";
		}
	}

	@RequestMapping(value = "/forget", method = RequestMethod.GET)
	public String forgetPage() {
		return "forget";
	}

	@RequestMapping(value = "/forget", method = RequestMethod.POST)
	public String forget(@RequestParam("username") String username,
	                    @RequestParam("password") String password,
	                    @RequestParam("confirmPassword") String confirmPassword,
	                    Model model) {
		if (username == null || username.trim().isEmpty()) {
			model.addAttribute("errorMsg", "用户名不能为空");
			model.addAttribute("username", username);
			return "forget";
		}
		if (password == null || password.trim().isEmpty()) {
			model.addAttribute("errorMsg", "新密码不能为空");
			model.addAttribute("username", username);
			return "forget";
		}
		if (password.length() < 6) {
			model.addAttribute("errorMsg", "新密码不能少于6位");
			model.addAttribute("username", username);
			return "forget";
		}
		if (!password.equals(confirmPassword)) {
			model.addAttribute("errorMsg", "两次密码输入不一致");
			model.addAttribute("username", username);
			return "forget";
		}
		String realpwd = loginservice.getpwdbyname(username);
		if (realpwd == null) {
			model.addAttribute("errorMsg", "用户名不存在");
			model.addAttribute("username", username);
			return "forget";
		}
		loginservice.updatePasswordByUsername(username, password);
		try {
			String encodedMsg = URLEncoder.encode("密码重置成功，请登录", StandardCharsets.UTF_8.toString());
			return "redirect:/login?msg=" + encodedMsg;
		} catch (Exception e) {
			return "redirect:/login?msg=密码重置成功，请登录";
		}
	}

	@RequestMapping("/sendEmailCode")
	@ResponseBody
	public String sendEmailCode(@RequestParam("email") String email, HttpSession session) {
		if (email == null || email.trim().isEmpty()) {
			return "邮箱不能为空";
		}
		// 生成6位验证码
		String code = String.format("%06d", new Random().nextInt(999999));
		String title = "注册验证码";
		String text = "您的注册验证码为：" + code + "，5分钟内有效。";
		boolean sent = MailUtils.sendMail(email, text, title);
		if (sent) {
			session.setAttribute("email_code", code);
			session.setAttribute("email_code_addr", email);
			session.setAttribute("email_code_time", System.currentTimeMillis());
			return "success";
		} else {
			return "邮件发送失败，请稍后重试";
		}
	}
  }
